<script setup>
import { ref, onMounted, watch } from "vue"
import { useGetTasksByMonthService } from '@/api/task'
import { useUserStore } from '@/stores/modules/user'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'

// 获取用户信息
const userStore = useUserStore()
console.log('登录用户id:', userStore.userId)
// 加载状态
const loading = ref(false)
// 当前选择的年份和月份
const selectedYear = ref(new Date().getFullYear())
const selectedMonth = ref(new Date().getMonth())
// 月份名称
const monthNames = [
  "一月",
  "二月",
  "三月",
  "四月",
  "五月",
  "六月",
  "七月",
  "八月",
  "九月",
  "十月",
  "十一月",
  "十二月",
]
// 星期名称
const weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"]
// 左上角的显示文本
const currentMonthText = ref(`${selectedYear.value}年 ${monthNames[selectedMonth.value]}`)
// 当月的日历数据
const calendarDays = ref([])
// 日程数据
const events = ref([])

// 处理月份变化
const handleMonthChange = (increment) => {
  let newMonth = selectedMonth.value + increment
  let newYear = selectedYear.value

  if (newMonth > 11) {
    newMonth = 0
    newYear++
  } else if (newMonth < 0) {
    newMonth = 11
    newYear--
  }

  selectedMonth.value = newMonth
  selectedYear.value = newYear
  currentMonthText.value = `${newYear}年 ${monthNames[newMonth]}`
  getTasksByMonth()
}

const getTasksByMonth = async () => {
  // 设置加载状态
  loading.value = true
  try {
    // 传入后端的日期，格式为xxxx-xx
    const month = (selectedMonth.value + 1).toString().padStart(2, '0')
    console.log('获取任务列表的用户ID:', userStore.userId)
    if (!userStore.userId) {
      console.log('用户未登录或用户ID不存在')
      events.value = []
      generateCalendarDays()
      return
    }
    const res = await useGetTasksByMonthService({ 
      user_id: userStore.userId, 
      month: `${selectedYear.value}-${month}` 
    })
    console.log('按月份获取任务列表:', res)
    events.value = res.data.data
    generateCalendarDays()
  } catch (error) {
    console.error('获取任务列表失败:', error)
    events.value = []
    generateCalendarDays()
  } finally {
    loading.value = false
  }
}

// 监听用户ID变化，当用户切换时重新获取任务列表
watch(() => userStore.userId, (newUserId, oldUserId) => {
  console.log('用户ID变化:', oldUserId, '->', newUserId)
  if (newUserId) {
    getTasksByMonth()
  } else {
    // 用户登出时清空事件列表
    events.value = []
    generateCalendarDays()
  }
}, { immediate: true })

getTasksByMonth()
// 点击事件状态
const showEventCard = ref(false)
const selectedEvent = ref(null)
// 生成日历数据
const generateCalendarDays = () => {
  calendarDays.value = []
  // 获取当月第一天
  const firstDay = new Date(selectedYear.value, selectedMonth.value, 1)
  // 获取当月第一天是星期几
  const firstDayOfWeek = firstDay.getDay()
  // 获取当月的总天数
  const daysInMonth = new Date(selectedYear.value, selectedMonth.value + 1, 0).getDate()
  // 添加上个月的剩余天数
  const prevMonthDays = new Date(selectedYear.value, selectedMonth.value, 0).getDate()
  for (let i = 0; i < firstDayOfWeek; i++) {
    const day = prevMonthDays - firstDayOfWeek + i + 1
    calendarDays.value.push({
      day,
      isCurrentMonth: false,
      events: [],
    })
  }
  // 添加当月的天数
  for (let i = 1; i <= daysInMonth; i++) {
    const dayEvents = events.value.filter((event) => {
      return event.finish_date.slice(-2) == i
    })
    calendarDays.value.push({
      day: i,
      isCurrentMonth: true,
      events: dayEvents,
    })
  }
  // 计算需要添加的下个月天数
  const remainingDays = 7 - (calendarDays.value.length % 7)
  if (remainingDays < 7) {
    for (let i = 1; i <= remainingDays; i++) {
      calendarDays.value.push({
        day: i,
        isCurrentMonth: false,
        events: [],
      })
    }
  }
}
// 点击事件
const handleEventClick = (event) => {
  console.log('点击事件:', event)
  selectedEvent.value = event
  showEventCard.value = true
}
// 关闭卡片
const closeEventCard = () => {
  showEventCard.value = false
}
onMounted(() => {
  getTasksByMonth()
})
</script>

<template>
  <div class="calendar-container">
    <!-- 加载状态 -->
    <div class="loading-overlay" v-if="loading">
      <div class="loading-spinner">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>加载中...</span>
      </div>
    </div>
    
    <div class="calendar-header">
      <div class="month-navigation">
        <el-icon class="month-arrow" @click="handleMonthChange(-1)"><ArrowLeft /></el-icon>
        <h2 class="month-title">{{ currentMonthText }}</h2>
        <el-icon class="month-arrow" @click="handleMonthChange(1)"><ArrowRight /></el-icon>
      </div>
    </div>
    <div class="calendar-grid">
      <!-- 星期 -->
      <div class="weekday-header" v-for="day in weekDays" :key="day">
        {{ day }}
      </div>
      <!-- 日历 -->
      <div
        v-for="(day, index) in calendarDays"
        :key="index"
        class="calendar-day"
        :class="{
          'current-month': day.isCurrentMonth,
          'other-month': !day.isCurrentMonth,
        }"
      >
        <div class="day-number">{{ day.day }}</div>
        <div class="day-events">
          <div
            class="event"
            v-for="(event, eventIndex) in day.events"
            :key="eventIndex"
            :class="{
              'event-isFinish': event.isFinished,
              'event-outdated': event.finish_date < new Date().toISOString().slice(0, 10),
            }"
            @click="handleEventClick(event)"
          >
            {{ event.title }}
          </div>
        </div>
      </div>
    </div>
    <!-- 事件详情弹窗 -->
    <div
      v-if="showEventCard"
      class="event-details-card"
      @click="closeEventCard"
    >
      <div class="event-card" @click.stop>
        <div class="event-card-header">
          <h3>事件详情</h3>
          <button class="close" @click="closeEventCard">x</button>
        </div>
        <div class="event-card-content">
          <p class="event-title">{{ selectedEvent.title }}</p>
          <p class="event-classify">分类： {{ selectedEvent.classify_name }}</p>
          <p class="event-isFinish" :style="{ color: selectedEvent.isFinished ? 'green' : 'red' }">{{ selectedEvent.isFinished ? '已完成' : '未完成' }}</p>
          <p class="event-date" 
           :style="{ color: !selectedEvent.isFinished && selectedEvent.finish_date < new Date().toISOString().slice(0, 10) ? 'red' : '' }"
          >
            完成日期：{{ selectedEvent.finish_date }}
          </p>
          <p class="event-date">
            创建日期：{{ selectedEvent.create_date.slice(0, 10) }}
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.calendar-container {
  width: 100%;
  height: 100vh;
  padding: 20px;
  background-color: #ffffff;
  overflow: auto;
  position: relative;
}

// 加载状态样式
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
  
  .loading-spinner {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    
    .is-loading {
      font-size: 32px;
      color: #466ff5;
    }
    
    span {
      color: #466ff5;
      font-size: 16px;
    }
  }
}

.calendar-header {
  margin-bottom: 20px;

  .month-navigation {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 20px;

    .month-arrow {
      font-size: 20px;
      cursor: pointer;
      border-radius: 50%;
      transition: all 0.3s ease;

      &:hover {
        background-color: #e6e6e6;
      }
    }
  }

  .month-title {
    font-size: 24px;
    color: #494747;
    margin: 0;
    min-width: 150px;
    text-align: center;
  }
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 10px;

  .weekday-header {
    text-align: center;
    font-weight: bold;
    padding: 10px;
  }

  .calendar-day {
    min-height: 120px;
    background-color: white;
    border: 1px solid #c4e5eb;
    border-radius: 4px;
    padding: 8px;
    position: relative;

    &.other-month {
      background-color: #f0f0f0;
      color: #aaa;
    }

    .day-number {
      position: absolute;
      top: 5px;
      left: 8px;
      font-size: 14px;
      font-weight: bold;
    }

    .day-events {
      margin-top: 25px;

      .event {
        background-color: #e1f5fe;
        border-left: 3px solid #03a9f4;
        padding: 5px 8px;
        margin-bottom: 5px;
        border-radius: 2px;
        font-size: 12px;

        &:hover {
          background-color: #b3e5fc;
        }
      }

      .event-outdated {
        background-color: rgb(247, 160, 160) !important;
        border-left: 3px solid red;
      }

      .event-isFinish {
        background-color: #ADF7D1 !important;
        border-left: 3px solid #03f4ac;
      }
    }
  }
}

.event-details-card {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.event-card {
  background-color: white;
  border-radius: 8px;
  width: 18rem;
  overflow: hidden;

  .event-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background-color: #03a9f4;
    color: white;

    h3 {
      margin: 0;
      font-size: 18px;
    }

    .close {
      background: none;
      border: none;
      color: white;
      font-size: 20px;
      cursor: pointer;
      padding: 0;
      line-height: 1;
    }
  }

  .event-card-content {
    padding: 16px;

    .event-title {
      font-size: 20px;
      font-weight: bold;
      margin-bottom: 8px;
    }
    .event-classify,
    .event-isFinish {
      font-size: 17px;
      margin-bottom: 8px;
    }

    .event-date {
      color: #666;
    }
  }
}
</style>
